package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 攻略文章实现
 *
 * @author totoro93
 * @date 2019-01-11
 **/
@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;
    @Override
    public PageInfo query(QueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(), queryObject.getPageSize(),queryObject.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(queryObject);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {

        //判断有无指定序列，未指定序列默认给到最后
        if (strategyDetail.getSequence()==null) {
            strategyDetail.setSequence(strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId())+1);
        }
        //判断状态，状态为发布时指定发布时间
        if (strategyDetail.getState()==StrategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(new Date());
        }
        //获取前端提交的攻略文章文本内容
        StrategyContent strategyContent = strategyDetail.getStrategyContent();
        if (strategyDetail.getId() != null) {
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //获取攻略文章id,设置到攻略文章文本内容
            strategyContent.setId(strategyDetail.getId());
            //更新攻略文章
            strategyContentMapper.updateByPrimaryKey(strategyContent);

        } else {
            strategyDetailMapper.insert(strategyDetail);
            //获取攻略文章id,设置到攻略文章文本内容
            strategyContent.setId(strategyDetail.getId());
            //新增攻略文章
            strategyContentMapper.insert(strategyContent);
        }

    }

    @Override
    public StrategyDetail selectDetailContentById(Long id) {


        return strategyDetailMapper.selectByPrimaryKey(id);
    }
}
